package com.example.pets_java.controller;

import com.example.pets_java.pojo.Pet;
import com.example.pets_java.service.PetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

@RestController
@RequestMapping("/api/pets")
public class PetController {

    @Autowired
    private PetService petService;

    @GetMapping("/owner/{ownerId}")
    public List<Pet> getPetsByOwnerId(@PathVariable int ownerId) {
        return petService.getPetsByOwnerId(ownerId);
    }

    @GetMapping("/owner")
    public List<Pet> getPetsForCurrentUser() {
        String userId = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return petService.getPetsByOwnerId(Integer.parseInt(userId));
    }

    @GetMapping("/{id}")
    public Pet getPetById(@PathVariable int id) {
        Pet pet = petService.getPetById(id);
        if (pet == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Pet not found with id " + id);
        }
        return pet;
    }

    @PostMapping("/add")
    public void addPet(@RequestBody Pet pet) {
        petService.addPet(pet);
    }

    @PutMapping("/update")
    public void updatePet(@RequestBody Pet pet) {
        petService.updatePet(pet);
    }

    @DeleteMapping("/delete/{id}")
    public void deletePet(@PathVariable int id) {
        petService.deletePet(id);
    }
}
